<?php

namespace App\Service\CommodityService;
use App\Service\AppService\SystemCacheConfigService;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Service\OrderService\OrderRouteService\Shopcainiao;
use App\Model\CommodityModel\SupplierCompany;
use Hyperf\DbConnection\Db;

/**
 * 行云供应商商品资料拉取
 * @author chenshubo
 */
class SupplierCommodityCainiaoPullLogService extends BaseService
{
    const PULL_FLAG = 'shopcainiao';
    const TIME_WAIT = 60;//分钟
    const PULL_USER_COUNT = 10;//每次同时拉取供应商的数量
    /**
     * 开启计划任务
     */
    public function runTask($SupplierID = 0)
    {
        //系统业务配置里面管控配置参数
        $config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('channel_task_user_limit');
        if( empty($config) ) {
            return Normal::returnCode(Normal::FAIL,'参数未配置');
        }
        //所有供应商拉取完成间隔时间
        $SupplierPullWaitTime = $config['SupplierPullWaitTime'];
        $SupplierPullWaitTime = $SupplierPullWaitTime > 0 ? $SupplierPullWaitTime : self::TIME_WAIT;
        //预计下次拉取商品时间
        $CommodityGetNetPeriod = date("Y-m-d H:i:s",time() + $SupplierPullWaitTime * 60 );
        
        $res = SupplierCommodityPullLogService::instance()->getWaitPullSupplierWareHouseInfosByThirdPartyPlatformCode(self::PULL_FLAG,$SupplierID);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        
        
        $suppliers = $res['data'];
        
        //获取供应商参数
        $SupplierIDs     = array_column($suppliers,'SupplierID');
        //初始化拉取状态
        $updateArr = [
            'CommodityGetTaskStatus'    => 0,
            'CommodityGetFinishCount'   => 0,
            'CommodityGetFinishUseTime' => 0.000,
        ];
        SupplierCompany::instance()->whereIn('ID',$SupplierIDs)->update($updateArr);
        
        //处理分类拉取情况
        foreach ($suppliers as  $supplier )
        {
            $innerPage = 1;
            $apiBody = $supplier['JsonBody'];
            $CommodityGetStartTime = microtime(true);
            $company_code    = $supplier['ThirdPartyPlatformCode'] ?: $supplier['SupplierCode'];
            $CommodityGetTotal = 0;
            while ( true )
            {
                //根据分类获取商品
                $queryBody = [
                    'page'          => $innerPage,
                    'limit'         => $apiBody['limit'] ?? 20,
                    'supplierID'    => $supplier['SupplierID'],
                ];
                
                try {
                    $resQuery = Shopcainiao::instance()->queryGoodsList(['apiBody'   => $apiBody,'queryBody' => $queryBody ]);
                    if( $resQuery['code'] != Normal::SUC ) {
                        SupplierCompany::instance()->where('ID',$supplier['SupplierID'])->update(['CommodityGetContents'=>$resQuery['msg'],'CommodityGetTaskStatus'=>3]);
                        break;
                    }
                    SupplierCompany::instance()->where('ID',$supplier['SupplierID'])->update(['CommodityGetContents'=>$resQuery['msg']]);
                } catch ( \Throwable $t ) {
                    SupplierCompany::instance()->where('ID',$supplier['SupplierID'])->update(['CommodityGetContents'=>$t->getMessage(),'CommodityGetTaskStatus'=>3]);
                    break;
                }
                if ($resQuery['data']['is_end']==false){
                    //动态更新已拉取的数据
                    $pull_count = count($resQuery['data']['list']);
                    $CommodityGetTotal += $pull_count;
                    $updateArr = [
                        'CommodityGetTaskStatus'    => 1,
                        'CommodityGetFinishCount'   => Db::raw("CommodityGetFinishCount+{$pull_count}"),
                        'CommodityGetTotal'         => $resQuery['data']['total']??0
                    ];
                    SupplierCompany::instance()->where('ID',$supplier['SupplierID'])->update($updateArr);
                    $MessageBody  = [
                        'SupplierID'        => $supplier['SupplierID'],
                        'SupplierCode'      => $company_code,
                        'IsFirstPage'       => $innerPage == 1 ? 1 : 0,
                        'DataPage'          => $innerPage,
                        'IsLastPage'        => 0,
                        'GoodsItemList'     => $resQuery['data']['list']
                    ];
                    SupplierCommodityPullLogService::instance()->publish($MessageBody);
                    $innerPage++;
                }else{
                    //更新总数量
                    $MessageBody  = [
                        'SupplierID'        => $supplier['SupplierID'],
                        'SupplierCode'      => $company_code,
                        'IsFirstPage'       => 0,
                        'DataPage'          => $innerPage,
                        'IsLastPage'        => 1,
                        'GoodsItemList'     => []
                    ];
                    SupplierCommodityPullLogService::instance()->publish($MessageBody);
                    //拉取完成
                    $updateArr = [
                        'CommodityGetTaskStatus'    => 2,
                        'CommodityGetContents'      => '拉取完成',
                        'CommodityGetFinishUseTime' => bcsub(microtime(true),$CommodityGetStartTime,3),
                        'CommodityGetNetPeriod'     => $CommodityGetNetPeriod
                    ];
                    SupplierCompany::instance()->where('ID',$supplier['SupplierID'])->update($updateArr);
                    break;
                }
            }
        }
        
        
        return Normal::returnCode(Normal::SUC,'拉取完成');
    }
}